/**
 * 
 */
package com.airnews.ticket.ui.login;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.airnews.ticket.R;
import com.airnews.ticket.model.FlightInfo;
import com.airnews.ticket.model.SearchFlight;
import com.airnews.ticket.model.UserResponseResult;
import com.airnews.ticket.net.WebAccessor;
import com.airnews.ticket.pay.util.BaseHelper;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.ui.Main;
import com.airnews.ticket.ui.flight.FlyOrderInput;
import com.airnews.ticket.ui.order.OrderList;
import com.mobclick.android.MobclickAgent;

/**
 * @author luoxz
 *
 */
public class Registration extends BaseActivity {
	private Button backBut;
	private Button registerButton;
	
	private EditText userName,password,comfigPassword,email,mobile;
	
	public static FlightInfo flight;//去程
	public static FlightInfo returnFlight;//回程
	public static SearchFlight searchFlight;
	public static String isOrderList;//是否从订单查询过来
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	public final int NORESULT = 6;
	public final int ORTHERRESULT =5;
	public final int SEARCH_ERROR=7;
	public final int USER_ERROR = 1;
	public final int PWD_ERROR = 2;
	public final int MOBILE_ERROR = 3;
	public final int EMAIL_ERROR = 4;
	public final int INPUT_ERROR = 9;
	
	public final String serviceType = "USER_REGIST";
	private SharedPreferences sp;
	private Toast toast;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		sp = getSharedPreferences("UserInfoB2C", Context.MODE_PRIVATE);
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(onClickListener);
		
		registerButton = (Button) findViewById(R.id.registerButton);
		registerButton.setOnClickListener(onClickListener);
		
//		userName = (EditText) findViewById(R.id.userName);
		password = (EditText) findViewById(R.id.password);
		comfigPassword = (EditText) findViewById(R.id.comfigPassword);
		email = (EditText) findViewById(R.id.email);
		mobile = (EditText) findViewById(R.id.mobile);
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					toast = Toast.makeText(Registration.this, "未能成功注册用户信息", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case SEARCH_ERROR:
					toast = Toast.makeText(Registration.this, (String)msg.obj, Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case ORTHERRESULT:
					toast = Toast.makeText(Registration.this, "网络超时或者其他错误", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case INPUT_ERROR:
					BaseHelper.showDialog(Registration.this, "提示", "请填写完整信息",
    						R.drawable.infoicon);
					break;
				case USER_ERROR:
					toast = Toast.makeText(Registration.this, "姓名应为2-6个中文字符或2-20个英文", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case PWD_ERROR:
					toast = Toast.makeText(Registration.this, "密码与确认密码不一致", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case MOBILE_ERROR:
					toast = Toast.makeText(Registration.this, "请输入正确的手机号码或者邮箱地址", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case EMAIL_ERROR:
					toast = Toast.makeText(Registration.this, "Email填写不正确", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
			}
		};
	}
	
	private OnClickListener onClickListener = new OnClickListener(){
		public void onClick(View v) {
			switch(v.getId()){
				case R.id.backBut:
					Intent intentR = new Intent();
					intentR.setClass(Registration.this, Login.class);
					Login.flight = flight;
					Login.searchFlight = searchFlight;
					Login.returnFlight = returnFlight;
					startActivity(intentR);
					break;
				case R.id.registerButton:{//注册
					register();
					break;
				}
				
			}
			
		}
	};
	
	private void register() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "正在注册用户信息...",true);
		final Thread thread = new Thread() {
			public void run() {
		        try {
//		        	String name = userName.getText().toString();
					String pwd = password.getText().toString();
					String cpwd = comfigPassword.getText().toString();
					String emailV = email.getText().toString();
					String mobileV = mobile.getText().toString();
					
					if ("".equals(mobileV) || "".equals(pwd) || "".equals(cpwd)){
	    				Message msg = new Message();
						msg.what = INPUT_ERROR;
						myHandler.sendMessage(msg);
						progressDialog.dismiss();
	    				return;
	    			}
//	    			if(!name.matches("(^[\u4e00-\u9fa5]{2,6}$)|(^[a-zA-z][a-zA-z\\s]{0,18}[a-zA-z]$)")){
//	    				Message msg = new Message();
//						msg.what = USER_ERROR;
//						myHandler.sendMessage(msg);
//						progressDialog.dismiss();
//	    				return;				
//	    			}
	    			if(!pwd.equals(cpwd)){
	    				Message msg = new Message();
						msg.what = PWD_ERROR;
						myHandler.sendMessage(msg);
						progressDialog.dismiss();
						return;
	    			}
	    			if(mobileV!=null && mobileV.length()>0){
						if (mobileV.matches("[0-9]{11}") || mobileV.matches("\\w+@(\\w+\\.)+[a-z]{2,3}")) {
							System.out.println("success");
						} else {
							Message msg = new Message();
							msg.what = MOBILE_ERROR;
							myHandler.sendMessage(msg);
							progressDialog.dismiss();
							return;
						}
	    			}
					UserResponseResult result = WebAccessor.userRegister("",pwd,mobileV,serviceType);
					System.out.println("Result = " + result.Result);
					if (progressDialog.isShowing()) {
						if (result== null) {
							Message msg = new Message();
							msg.what = NORESULT;
							myHandler.sendMessage(msg);
						}else if(!"0".equals(result.Result)){
							Message msg = new Message();
							msg.what = SEARCH_ERROR;
							msg.obj = result.ErrorDescription;
							myHandler.sendMessage(msg);
						} else if("0".equals(result.Result)){
							Intent intent = new Intent();
			    			
			    			//String emailR = result.UserName.split(",")[0];
			    			String userIdR = result.UserID;
			    			 Log.i("Login userId", userIdR);
						     Log.i("Login pwd", pwd);
			    			sp.edit().putString("userId",userIdR).commit();
							sp.edit().putString("userPwd",pwd).commit();
							sp.edit().putString("ASToken",result.ASToken).commit();
					       
							Bundle bundle=new  Bundle();
			    			bundle.putString("loginName", result.UserName);
			    			bundle.putString("isLoninOK", "OK");
			    			bundle.putString("autoLogin", null);
			    			sp.edit().putString("loginName",result.UserName).commit();
			    			sp.edit().putString("isLoninOK","OK").commit();
			    			sp.edit().putString("isAutoLogin",null).commit();
			    			intent.putExtras(bundle);
			    			
			    			if(flight!=null){
				    			intent.setClass(Registration.this, FlyOrderInput.class);
				    			FlyOrderInput.flight = flight;
				    			FlyOrderInput.searchFlight = searchFlight;
				    			FlyOrderInput.returnFlight = returnFlight;
			    			} else if(isOrderList!=null){
								Intent it = new Intent(Registration.this, OrderList.class);
								startActivity(it);
							} else {
			    				intent.setClass(Registration.this, Main.class);
			    			}
							
			    			startActivity(intent);
						} else {
							Message msg = new Message();
							msg.what = ORTHERRESULT;
							msg.obj = result.ErrorDescription;
							myHandler.sendMessage(msg);
						}
						progressDialog.dismiss();
					}
		        } catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
